<?php

namespace app\admin\controller\system;

use app\admin\controller\AuthController;
use app\model\system\SystemLog;
use app\model\system\SystemMenus;
use app\Request;
use albert\services\FormBuilder;
use albert\services\JsonService;
use albert\services\UtilService;
use Exception;
use FormBuilder\exception\FormBuilderException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 菜单管理类
 * Class MenuController
 * @package app\admin\controller\system
 */
class MenuController extends AuthController
{
    /**
     * 列表展示页
     * Author: Albert3306
     * Date: 2021/1/4
     * @return string
     */
    public function index(): string
    {
        return $this->fetch('system/menu');
    }

    /**
     * 列表数据
     * Author: Albert3306
     * Date: 2021/4/28
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function lst(): string
    {
        $params = UtilService::param([
            ['pid', 0],
            ['is_show', ''],
            ['keywords', ''],
        ]);
        $data = SystemMenus::getLayUIAllList($params);
        return JsonService::successLayUI($data['count'], $data['data']);
    }

    /**
     * 添加展示页
     * Author: Albert3306
     * Date: 2021/5/1
     * @param int $cid
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws FormBuilderException
     */
    public function create(int $cid = 0): string
    {
        $f = [];
        $f[] = FormBuilder::input('name', '菜单名称')->required('菜单名称必填');
        $f[] = FormBuilder::select('pid', '父级id', $cid)->setOptions(function () {
            $menuList = SystemMenus::field(['id', 'pid', 'name'])->order('sort DESC,id ASC')->select()->toArray();
            $list = sort_list_tier($menuList, 0, 'pid', 'name');
            $menus = [['value' => 0, 'label' => '顶级菜单']];
            foreach ($list as $menu) {
                $menus[] = ['value' => $menu['id'], 'label' => $menu['html'] . $menu['name']];
            }
            return $menus;
        })->filterable(1);
        $f[] = FormBuilder::select('module', '模块名')->options([['label' => '总后台', 'value' => 'admin']]);
        if ($cid) $controller = SystemMenus::where('id', $cid)->value('controller') ?: '';
        else $controller = '';
        $f[] = FormBuilder::input('controller', '控制器名', $controller);
        if (!empty($controller)) {
            $controller = preg_replace_callback('/([.]+([a-z]{1}))/i', function ($matches) {
                return '\\' . strtoupper($matches[2]);
            }, $controller);
            if (class_exists('\app\admin\controller\\' . $controller)) {
                $list = get_this_class_methods('\app\admin\controller\\' . $controller);
                $f[] = FormBuilder::select('action', '方法名')->setOptions(function () use ($list) {
                    $menus = [['value' => 0, 'label' => '默认函数']];
                    foreach ($list as $menu) {
                        $menus[] = ['value' => $menu, 'label' => $menu];
                    }
                    return $menus;
                })->filterable(1);
            } else {
                $f[] = FormBuilder::input('action', '方法名');
            }
        } else {
            $f[] = FormBuilder::input('action', '方法名');
        }
        $f[] = FormBuilder::input('route', '路由地址');
        $f[] = FormBuilder::input('params', '参数');
        $f[] = FormBuilder::frameInputOne('icon', '图标', '/admin/widget/icon?fodder=icon')->icon('ionic')->height('500px');
        $f[] = FormBuilder::number('sort', '排序', 0);
        $f[] = FormBuilder::radio('is_show', '是否菜单', 0)->options([['value' => 0, 'label' => '隐藏'], ['value' => 1, 'label' => '显示(菜单只显示三级)']]);
        $form = FormBuilder::make_post_form('添加权限', $f, '/admin/system/menu/save', 3);
        return $this->fetch('public/form-builder', [
            'form' => $form
        ]);
    }

    /**
     * 添加保存
     * Author: Albert3306
     * Date: 2021/5/1
     * @return string
     */
    public function save(): string
    {
        $data = UtilService::param([
            ['pid', 0],
            ['sort', 0],
            ['icon', ''],
            ['name', ''],
            ['route', ''],
            ['action', ''],
            ['params', ''],
            ['is_show', 1],
            ['controller', ''],
            ['module', 'admin'],
        ]);
        if (!$data['name']) return JsonService::fail('请输入菜单名称！');
        SystemMenus::create($data);
        return JsonService::successful('添加菜单成功！');
    }

    /**
     * 编辑展示页
     * Author: Albert3306
     * Date: 2021/5/1
     * @param $id
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws FormBuilderException
     * @throws ModelNotFoundException
     */
    public function edit($id): string
    {
        $info = SystemMenus::get($id);
        if (!$info) return JsonService::fail('数据不存在!');
        $f = [];
        $f[] = FormBuilder::input('name', '按钮名称', $info['name']);
        $f[] = FormBuilder::select('pid', '父级id', (string)$info->getData('pid'))->setOptions(function () use ($id) {
            $menuList = SystemMenus::field(['id', 'pid', 'name'])->order('sort DESC,id ASC')->select()->toArray();
            $list = sort_list_tier($menuList, 0, 'pid', 'name');
            $menus = [['value' => 0, 'label' => '顶级按钮']];
            foreach ($list as $menu) {
                $menus[] = ['value' => $menu['id'], 'label' => $menu['html'] . $menu['name']];
            }
            return $menus;
        })->filterable(1);
        $f[] = FormBuilder::select('module', '模块名', $info['module'])->options([['label' => '总后台', 'value' => 'admin']]);
        $f[] = FormBuilder::input('controller', '控制器名', $info['controller']);
        if (!empty($info['controller'])) {
            $controller = preg_replace_callback('/([.]+([a-z]{1}))/i', function ($matches) {
                return '\\' . strtoupper($matches[2]);
            }, $info['controller']);
            if (class_exists('\app\admin\controller\\' . $controller)) {
                $list = get_this_class_methods('\app\admin\controller\\' . $controller);

                $f[] = FormBuilder::select('action', '方法名', (string)$info->getData('action'))->setOptions(function () use ($list) {
                    $menus = [['value' => 0, 'label' => '默认函数']];
                    foreach ($list as $menu) {
                        $menus[] = ['value' => $menu, 'label' => $menu];
                    }
                    return $menus;
                })->filterable(1);
            } else {
                $f[] = FormBuilder::input('action', '方法名', $info['action']);
            }
        } else {
            $f[] = FormBuilder::input('action', '方法名');
        }
        $f[] = FormBuilder::input('route', '路由地址', $info['route']);
        $f[] = FormBuilder::input('params', '参数', SystemMenus::paramStr($info['params']));
        $f[] = FormBuilder::frameInputOne('icon', '图标', '/admin/widget/icon?fodder=icon', $info['icon'])->icon('ionic')->height('500px');
        $f[] = FormBuilder::number('sort', '排序', $info['sort']);
        $f[] = FormBuilder::radio('is_show', '是否菜单', $info['is_show'])->options([['value' => 0, 'label' => '隐藏'], ['value' => 1, 'label' => '显示(菜单只显示三级)']]);
        $form = FormBuilder::make_post_form('添加权限', $f, '/admin/system/menu/update/' . $id, 1);
        return $this->fetch('public/form-builder', [
            'form' => $form
        ]);
    }

    /**
     * 编辑保存
     * Author: Albert3306
     * Date: 2021/5/1
     * @param $id
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function update($id): string
    {
        $data = UtilService::param([
            ['pid', 0],
            ['sort', 0],
            ['icon', ''],
            ['name', ''],
            ['route', ''],
            ['action', ''],
            ['params', ''],
            ['is_show', 1],
            ['controller', ''],
            ['module', 'admin'],
        ]);
        if (!$data['name']) return JsonService::fail('请输入按钮名称');
        if (!SystemMenus::get($id)) return JsonService::fail('编辑的记录不存在！');
        SystemMenus::edit($data, $id);
        return JsonService::successful('修改成功！');
    }

    /**
     * 删除
     * Author: Albert3306
     * Date: 2021/5/1
     * @param $id
     * @return string
     * @throws Exception
     */
    public function delete($id): string
    {
        if (!$id) return $this->failed('参数错误，请重新打开！');
        $res = SystemMenus::delMenu($id);
        if (!$res)
            return JsonService::fail(SystemMenus::getErrorInfo('删除失败，请稍候再试！'));
        else
            return JsonService::successful('删除成功！');
    }
}